<?php
namespace app\site\controller;

use app\common\model\ShopExpressModel;
use app\common\model\ShopOrderGoodsModel;
use app\common\model\ShopOrderLogModel;
use app\common\model\ShopOrderModel;
use app\common\model\UserModel;
use think\Request;

class ShopOrderController extends BaseController
{

    private $orderModel;
    private $orderLogModel;
    private $orderGoodsModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->orderModel      = new ShopOrderModel();
        $this->orderGoodsModel = new ShopOrderGoodsModel();
        $this->orderLogModel   = new ShopOrderLogModel();
    }

    /**
     * 获取订单详情
     * @param $orderSn
     */
    private function getOrderDetail($orderSn)
    {
        $orderInfo              = $this->orderModel->where('order_sn', $orderSn)->find();
        $orderInfo['item_list'] = $this->orderGoodsModel->where('order_id', $orderInfo['order_id'])->select();
        $orderInfo['log_list']  = $this->orderLogModel->where('order_id', $orderInfo['order_id'])->select();
        return $orderInfo;
    }

    /**
     * 首页
     */
    public function index()
    {
        $map               = [];
        $query             = [];
        $map['site_id'] = $this->getSiteId();
        $query['site_id'] = $this->getSiteId();
        //时间
        $query['bdate'] = $this->request->param('bdate');
        $query['edate'] = $this->request->param('edate');
        $bdate = 0;
        $edate = strtotime(date('Y-m-d').'23:59:59');
        if(!empty($query['bdate'])){
            $bdate = strtotime($query['bdate'].' 0:00:00');
        }
        if(!empty($query['edate'])){
            $edate = strtotime($query['edate'].' 23:59:59');
        }
        $map['create_time'] = ['between',[$bdate,$edate]];
        //订单来源
        $query['order_form']           = $this->request->param('order_from');
        if(!empty($query['order_form'])){
            $map['order_form'] = $query['order_form'];
        }
        //订单字段查询
        $query['searchkey'] = $this->request->param('searchkey');
        $query['searchquery'] = $this->request->param('searchquery');
        $query['searchvalue'] = $this->request->param('searchvalue');
        if(!empty($query['searchkey']) && !empty($query['searchquery']) && !empty($query['searchvalue'])){
            if($query['searchquery']=='like'){
                $map[$query['searchkey']] = ['like','%'.$query['searchvalue'].'%'];
            }
            if($query['searchquery']=='eq'){
                $map[$query['searchkey']] = $query['searchvalue'];
            }
        }
        //订单类型
        $query['order_genre']           = $this->request->param('order_genre', 0);
        if ($query['order_genre'] == 1) { //未付款
            $map['pay_status'] = 0;
        }
        if ($query['order_genre'] == 2) { //已付款未发货
            $map['pay_status'] = 1;
            $map['shipping_status'] = 0;
        }
        if ($query['order_genre'] == 3) { //已付款已发货
            $map['pay_status'] = 1;
            $map['shipping_status'] = 1;
            $map['order_status'] = 1;
        }
        if ($query['order_genre'] == 4) { //已完成
            $map['order_status'] = 2;
        }
        if ($query['order_genre'] == 5) { //积分订单
            $map['order_type'] = 3;
        }
        if ($query['order_genre'] == 6) { //集采订单
            $map['order_type'] = 4;
        }
        if ($query['order_genre'] == 7) { //竞拍订单
            $map['order_type'] = 5;
        }
        if ($query['order_genre'] == 8) { //退款单
            $map['refund_status'] = ['>', 0];
        }
        if ($query['order_genre'] == 9) { //已作废
            $map['order_status'] = -1;
        }
        $list           = $this->orderModel->where($map)->order('create_time desc')->paginate(12, false, [
            'query' => $query,
        ]);
        //echo $this->orderModel->getLastSql();
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }

    /**
     * 处理订单
     */
    public function orderHander()
    {
        $orderSn   = $this->request->param('order_sn');
        $orderInfo = $this->getOrderDetail($orderSn);
        $this->assign('orderInfo', $orderInfo);
        return $this->fetch();
    }

    /**
     * 订单支付
     * @return mixed
     */
    public function orderPay()
    {
        if ($this->request->isAjax()) {
            $rule   = [
                'payment_time' => 'require|date',
                'action_name'  => 'require',
                'pay_code'     => 'require',
                'log_msg'      => 'require',
            ];
            $data   = $this->request->param();
            $result = $this->validate($data, $rule);
            if (true !== $result) {
                $this->error($result);
            }
            $result = $this->orderModel->payOrder($data['action_name'], $data['order_sn'], $data['pay_code'],$data['log_msg'],strtotime($data['payment_time']));
            if ($result === false) {
                $this->error($this->orderModel->getError());
            }
            $this->success('操作成功！');
        }
        $userModel  = new UserModel();
        $orderId    = $this->request->param('order_id/d');
        $actionName = $userModel->where('uid', $this->getUid())->value('username');
        $orderInfo  = $this->orderModel->get($orderId);
        $this->assign('actionName', $actionName);
        $this->assign('orderInfo', $orderInfo);
        return $this->fetch();
    }

    /**
     * 订单发货
     */
    public function orderDelivery()
    {
        if ($this->request->isAjax()) {
            $rule   = [
                'shipping_time'   => 'require|date',
                'action_name'     => 'require',
                'express_code'    => 'require',
                'shipping_code'   => 'require',
                'deliver_explain' => 'require',
            ];
            $data   = $this->request->param();
            $result = $this->validate($data, $rule);
            if (true !== $result) {
                $this->error($result);
            }
            $result = $this->orderModel->deliveryOrder($data['action_name'], $data);
            if ($result === false) {
                $this->error($this->orderModel->getError());
            }
            $this->success('操作成功！');
        }
        $userModel   = new UserModel();
        $expressList = cache('express');
        $orderId     = $this->request->param('order_id/d');
        $actionName  = $userModel->where('uid', $this->getUid())->value('username');
        $orderInfo   = $this->orderModel->get($orderId);
        $this->assign('actionName', $actionName);
        $this->assign('expressList', $expressList);
        $this->assign('orderInfo', $orderInfo);
        return $this->fetch();
    }

    /**
     * 确认收货
     */
    public function orderFinnshed()
    {
        $userModel  = new UserModel();
        $orderId    = $this->request->param('order_id/d');
        $actionName = $userModel->where('uid', $this->getUid())->value('username');
        $result     = $this->orderModel->finnshedOrder($actionName, $orderId);
        if ($result === false) {
            $this->error($this->orderModel->getError());
        }
        $this->success('操作成功！');
    }

    /**
     * 关闭订单
     */
    public function orderClose()
    {
        $userModel  = new UserModel();
        $orderId    = $this->request->param('order_id/d');
        $actionName = $userModel->where('uid', $this->getUid())->value('username');
        $result     = $this->orderModel->closeOrder($actionName, $orderId);
        if ($result === false) {
            $this->error($this->orderModel->getError());
        }
        $this->success('操作成功！');
    }

    /**
     *订单退款
     */
    public function orderReturn()
    {
        if ($this->request->isAjax()) {
            $rule   = [
                'action_name'   => 'require',
                'refund_amount' => 'require',
                'refund_type'   => 'require',
                'buyer_message' => 'require',
            ];
            $data   = $this->request->param();
            $result = $this->validate($data, $rule);
            if (true !== $result) {
                $this->error($result);
            }
            $result = $this->orderModel->addRefundOrder($data['action_name'], $data);
            if ($result === false) {
                $this->error($this->orderModel->getError());
            }
            $this->success('操作成功！');
        }
        $userModel  = new UserModel();
        $orderId    = $this->request->param('order_id/d');
        $actionName = $userModel->where('uid', $this->getUid())->value('username');
        $orderInfo  = $this->orderModel->get($orderId);
        $this->assign('actionName', $actionName);
        $this->assign('orderInfo', $orderInfo);
        return $this->fetch();
    }

    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $orderSn   = $this->request->param('order_sn');
        $orderInfo = $this->getOrderDetail($orderSn);
        $this->assign('orderInfo', $orderInfo);
        return $this->fetch();
    }

    /**
     * 打印订单
     */
    public function orderPrint()
    {
        $orderSn   = $this->request->param('order_sn');
        $orderInfo = $this->getOrderDetail($orderSn);
        $this->assign('orderInfo', $orderInfo);
        return $this->fetch();
    }

    /**
     * 批量确认
     */
    public function orderConfirm()
    {
        $userModel  = new UserModel();
        $actionName = $userModel->where('uid', $this->getUid())->value('username');
        $orderIds   = $this->request->param('order_id');
        $result     = $this->orderModel->confirmOrder($actionName, $orderIds);
        if ($result === false) {
            $this->error($this->orderModel->getError());
        }
        $this->success('操作成功！');
    }

    /**
     * 删除订单
     */
    public function orderDel()
    {
        $orderIds = $this->request->param('order_id');
        if (is_numeric($orderIds)) {
            $orderInfo = $this->orderModel->find($orderIds);
            if ($orderInfo['order_status'] == 0 && $orderInfo['pay_status'] == 0) {
                $this->orderModel->delOrder($orderIds);
                $this->success('删除成功！');
            } else {
                $this->error('只有未付款并未确认得订单可删除！');
            }
        } else {
            $orderIds = explode(',', $orderIds);
            $num      = 0;
            foreach ($orderIds as $orderId) {
                $orderInfo = $this->orderModel->find($orderId);
                if ($orderInfo['order_status'] == 0 && $orderInfo['pay_status'] == 0) {
                    $this->orderModel->delOrder($orderId);
                    $num += 1;
                }
            }
            if ($num > 0) {
                $this->success("操作成功,成功删除{$num}条数据！");
            } else {
                $this->error('只有未付款并未确认得订单可删除！');
            }
        }

    }

}
